<template>
  <div ref="editorRef" class="monaco-editor-container" />
</template>

<script setup lang="ts">
import * as monaco from 'monaco-editor'
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'

const props = defineProps<{
  code: string
  language: string
  theme?: string
  readOnly?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:code', value: string): void
}>()

const editorRef = ref<HTMLElement | null>(null)
let editor: monaco.editor.IStandaloneCodeEditor | null = null

onMounted(() => {
  if (editorRef.value) {
    editor = monaco.editor.create(editorRef.value, {
      value: props.code,
      language: props.language,
      theme: props.theme || 'vs',
      readOnly: props.readOnly ?? false,
      automaticLayout: true
    })

    editor.onDidChangeModelContent(() => {
      emit('update:code', editor!.getValue())
    })
  }
})

onBeforeUnmount(() => {
  editor?.dispose()
})

watch(
  () => props.language,
  (newLang) => {
    if (editor) {
      monaco.editor.setModelLanguage(editor.getModel()!, newLang)
    }
  }
)

watch(
  () => props.code,
  (newCode) => {
    if (editor && editor.getValue() !== newCode) {
      editor.setValue(newCode)
    }
  }
)
</script>

<style>
.monaco-editor-container {
  width: 100%;
  height: 100%;
}
</style>
